const _ = require('lodash');
const fs = require('fs-extra');
const path = require('path');
const config = require('./config');
const dist = './dist';

fs.emptyDirSync(dist);
for (const menu of config.menus) {
  for (const subMenu of menu.subMenus) {
    for (const group of subMenu.groups) {
      for (const i in group.pages) {
        const page = group.pages[i];
        const dir = path.join(dist, menu.name, subMenu.name, group.name);
        fs.ensureDirSync(dir);
        const file = path.join(dir, `${_.padStart(+i+1, 2, 0)}_${page.name}.md`);
        const src = page.path && path.join('docs', page.path)
        
        if (src && fs.existsSync(src)) {
          fs.copyFileSync(src, file);
          try {
            fs.copySync(path.join(path.dirname(src), 'img'), path.join(dir, 'img'));
          } catch (e) {}
        } else if (page.content) {
          fs.writeFileSync(file, page.content, 'utf-8');
        } else {
          fs.writeFileSync(file, `### ${page.name}\n根据课堂实际情况指定课稿`, 'utf-8');
        }
      }
    }
  }
}
